package edu.uni.dormitory.controller;

import com.github.pagehelper.PageInfo;
import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.bean.ResultType;
import edu.uni.dormitory.bean.LiveArea;
import edu.uni.dormitory.bean.StudentBed;
import edu.uni.dormitory.dto.Query;
import edu.uni.dormitory.globalbean.AreaVo;
import edu.uni.dormitory.globalbean.BedVo;
import edu.uni.dormitory.globalbean.RoomVo;
import edu.uni.dormitory.globalbean.StudentBedClassVo;
import edu.uni.dormitory.service.AreaService;
import edu.uni.dormitory.service.BedService;
import edu.uni.example.bean.Product;
import edu.uni.userBaseInfo1.bean.Employee;
import edu.uni.userBaseInfo1.bean.Field;
import edu.uni.userBaseInfo1.service.EmployeeService;
import edu.uni.userBaseInfo1.service.FieldService;
import edu.uni.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 陈楚城
 * @create 2019.05.01
 * @function 宿舍区
 */
@Api(description = "宿舍区信息模块")
@Controller
@RequestMapping("json/dorm/area")
public class AreaController{
    @Autowired
    private AreaService areaService;
    @Autowired
    private FieldService fieldService;
    @Autowired
    private BedService bedService;
    @Autowired
    private RedisCache cache;
    @Autowired
    private AuthService authService;
    @Autowired
    private EmployeeService employeeService;
    /**
     * 内部类，专门用来管理每个方法所对应缓存的名称。
     */
    static class CacheNameHelper{
        // dorm_area_{id}
        private static final String Receive_CacheNamePrefix = "dorm_area_";
        // dorm_area_listByPage_{页码}
        private static final String ListByPage_CacheNamePrefix = "dorm_area_listByPage_";
    }

    /**
     * 通过主键获取某条宿舍区记录
     */
    @ApiOperation(value = "根据id获取宿舍区信息", notes = "未测试")
    @GetMapping("{id}")
    public void getAreaById(@PathVariable("id")long id, HttpSession session,HttpServletResponse response)throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.Receive_CacheNamePrefix+id;
       // String json = cache.get(cacheName);
        String json=null;
        if(json == null){
            AreaVo liveArea=areaService.selectLiveArea(id);
            json = Result.build(ResultType.Success).appendData("livearea", liveArea).convertIntoJSON();
            if(liveArea != null){
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
       // return Result.build(Success);
    }
    /**
     * 宿管中心获取所有宿舍区记录
     */
    @ApiOperation(value = "宿管中心获取所有宿舍区记录", notes = "未测试")
    @GetMapping("areaList/{universityId}")
    public void getareaList(@PathVariable long universityId, HttpSession session,HttpServletResponse response)throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.Receive_CacheNamePrefix+id;
        // String json = cache.get(cacheName);

        String json=null;
        if(json == null){
            List<AreaVo> list=areaService.selectAreaAll(universityId);

            for(AreaVo AreaVo:list){
                if(AreaVo.getType()==0){
                    AreaVo.setSex("女");
                }else
                    AreaVo.setSex("男");

            }
            json = Result.build(ResultType.Success).appendData("list", list).convertIntoJSON();
            if(list != null){
                //cache.set(cacheName, json);

            }
        }
        response.getWriter().write(json);
        // return Result.build(Success);
    }


    /**
     * 根据宿舍区id查询到这个宿舍区的房间
     *
     */
    @ApiOperation(value = "根据宿舍区id查询到这个宿舍区的所有房间", notes = "未测试")
    @GetMapping("RoomList/{areaId}")
    public void getRoomList(@PathVariable long areaId, HttpSession session,HttpServletResponse response)throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.Receive_CacheNamePrefix+id;
        // String json = cache.get(cacheName);
        String json=null;
        if(json == null){
            List<Field> list=fieldService.selectRoom(areaId);
            List<RoomVo> list1= new ArrayList<RoomVo>();
            //AreaVo areaVo=areaService.selectLiveArea(areaId);
            for(Field field:list){
                RoomVo roomVo=new RoomVo();
                roomVo.setId(field.getId());
                roomVo.setRoom(field.getRoom());
                roomVo.setBedNumber(bedService.selectbedNumber(field.getId()));
                roomVo.setPersonNumber(bedService.selectpersonNumber(field.getId()));
                list1.add(roomVo);
            }
            json = Result.build(ResultType.Success).appendData("list", list1).convertIntoJSON();
            if(list1 != null){
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
        // return Result.build(Success);
    }
    /**
     * 根据宿管employeeid查询到这个宿舍区的房间
     *这个是宿管登录的
     */
    @ApiOperation(value = "根据宿管employeeid查询到这个宿舍区的房间", notes = "未测试")
    @GetMapping("RoomList")
    public void getRoomList1(HttpSession session,HttpServletResponse response)throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //String cacheName =CacheNameHelper.Receive_CacheNamePrefix+id;
        // String json = cache.get(cacheName);
       // long employeeId=1;//登录人的身份
        User user = authService.getUser();
        List<Employee> employees=employeeService.selectByUserId(user.getId());
        long employeeId=employees.get(0).getId();
        String json=null;
        if(json == null){
            List<Field> list=fieldService.selectRoom(areaService.selectAreaIdByEid(employeeId).getAreaId());
            List<RoomVo> list1= new ArrayList<RoomVo>();
            AreaVo areaVo=areaService.selectLiveArea(areaService.selectAreaIdByEid(employeeId).getAreaId());
            for(Field field:list){
                RoomVo roomVo=new RoomVo();
                roomVo.setId(field.getId());
                roomVo.setRoom(field.getRoom());
                roomVo.setBedNumber(bedService.selectbedNumber(field.getId()));
                roomVo.setPersonNumber(bedService.selectpersonNumber(field.getId()));
                list1.add(roomVo);
            }
            json = Result.build(ResultType.Success).appendData("list", list1).appendData("areaVo",areaVo).convertIntoJSON();
            if(list1 != null){
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
        // return Result.build(Success);
    }
    /**
     * 分页获取宿舍区信息
     */
    @ApiOperation(value = "根据页码获取宿舍区信息", notes = "未测试")
    @GetMapping("list/{pageNum}/{universityId}")
    public void getAreaList(@PathVariable Integer pageNum ,@PathVariable long universityId, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
       // String cacheName = CacheNameHelper.ListByPage_CacheNamePrefix + pageNum;
        //String json = cache.get(cacheName);
        String json=null;
        if(json == null){
            PageInfo<AreaVo> pageInfo =areaService.selectPage(pageNum,universityId);
            json = Result.build(ResultType.Success).appendData("pageInfo", pageInfo).convertIntoJSON();
            if(pageInfo != null) {
                //cache.set(cacheName, json);
            }
        }
        response.getWriter().write(json);
        //return Result.build(Success);
    }
    /**
     * 新增宿舍区
     */
    @ApiOperation(value = "新增宿舍区", notes = "未测试")
    @PostMapping("")
    public Result addArea(LiveArea liveArea, HttpSession session){
        if(liveArea !=null){
            boolean success =areaService.update(liveArea);
            if(success){
               // cache.deleteByPaterm(CacheNameHelper.Receive_CacheNamePrefix+ "*");
                cache.deleteByPaterm(CacheNameHelper.ListByPage_CacheNamePrefix+ "*");
                return Result.build(ResultType.Success);
            }else{
                return Result.build(ResultType.Failed);
            }

        }
        return Result.build(ResultType.ParamError);
        //System.out.println(liveArea);
        //return Result.build(Success);
    }
    /**
     * 删除宿舍区
     */
    @ApiOperation(value = "删除宿舍区信息", notes = "未测试")
    @DeleteMapping("{id}")
    public Result removeArea(@PathVariable("id")Integer id,HttpSession session){
        boolean success = areaService.delete(id);
        if(success){
            cache.delete(CacheNameHelper.Receive_CacheNamePrefix + id);
            cache.deleteByPaterm(CacheNameHelper.ListByPage_CacheNamePrefix + "*");
            return Result.build(ResultType.Success);
        }else{
            return Result.build(ResultType.Failed);
        }
    }
    /**
     * 修改宿舍区信息
     */
    @ApiOperation(value = "修改宿舍区信息", notes = "")
    @PutMapping()
    @ResponseBody
    public Result updateLiveArea(@RequestBody(required = false) LiveArea liveArea){

        if(liveArea != null && liveArea.getId() != null){
            boolean success = areaService.update(liveArea);
            if(success){
                cache.delete(CacheNameHelper.Receive_CacheNamePrefix + liveArea.getId());
                cache.deleteByPaterm(CacheNameHelper.ListByPage_CacheNamePrefix + "*");
                return Result.build(ResultType.Success);
            }else{
                return Result.build(ResultType.Failed);
            }
        }
        return Result.build(ResultType.ParamError);
    }
}
